package com.liziguo.lzgfp.system.codec;

import com.liziguo.lzgfp.system.util.AESUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: Liziguo
 * @Date: 2021/12/27 22:20
 */
public class AESDecoder extends MessageToMessageDecoder<ByteBuf> {

    private final String aesKey;

    public AESDecoder(String aesKey) {
        this.aesKey = aesKey;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        list.add(Unpooled.copiedBuffer(AESUtil.decrypt(bytes, aesKey)));
    }

//    public static void main(String[] args) {
//        String str = "李子果";
//        ByteBuf buf = Unpooled.buffer(9);
//        System.out.println(buf.capacity());
//        buf.writeBytes(str.getBytes(StandardCharsets.UTF_8));
//        System.out.println(buf.readableBytes());
//        System.out.println(buf.capacity());
//
//        System.out.println("----------------------------------");
//
//        ByteBuf buf1 = Unpooled.copiedBuffer(str.getBytes(StandardCharsets.UTF_8));
//        System.out.println(buf1.readableBytes());
//        System.out.println(buf1.capacity());
//    }

    public static void main(String[] args) {
        String str = "李子果";
        ByteBuf buf = Unpooled.buffer();
        ByteBuf buf1 = buf.writeBytes(str.getBytes(StandardCharsets.UTF_8));
        System.out.println(buf == buf1);
        System.out.println(buf);
        System.out.println(buf1);
        System.out.println(buf.readableBytes());
        System.out.println(buf1.readableBytes());
        System.out.println("-------------");

        ByteBuf buf2 = buf.readBytes(str.getBytes(StandardCharsets.UTF_8));
        System.out.println(buf2 == buf1);
        System.out.println(buf2);
        System.out.println(buf1);
        System.out.println(buf2.readableBytes());
        System.out.println(buf1.readableBytes());
    }
}
